<?php

/**
 * @author langkhach
 * @copyright 2011
 */

class PGVariable{
    var $aVariable = array();
    var $hasUpdate = false;
    
    function PGVariable(){
      global $database;
      
      //$this->aVariable = CacheLib::get('pg_variable');
      //$this->aVariable = false;
      if (!$this->aVariable){
        $aVariable = array();
        $res = $database->db_query("SELECT * FROM variables");
        while ($var = $database->db_fetch_assoc($res)){
          $key = $var['variable_name']; unset($var['variable_name']);
          $this->aVariable[$key] = $var;
        }        
        //CacheLib::set('pg_variable', $this->aVariable, 3600);
      }
    }
    
    public function get($key, $default=""){
      return isset($this->aVariable[$key])?$this->aVariable[$key]['variable_value']:$default;
    }
    
    public function getData($key){
      return isset($this->aVariable[$key])?$this->aVariable[$key]:false;
    }
    
    public function set($key, $value, $log=''){
      global $database;
      
      $time = time();
      if (isset($this->aVariable[$key])){
        $this->aVariable[$key]['variable_value'] = $value;
        $this->aVariable[$key]['variable_updated'] = $time;
        $this->aVariable[$key]['variable_log'] = $log;
        
        //CacheLib::set('pg_variable', $this->aVariable);
        
        return $database->db_query("UPDATE variables SET variable_value='%s', variable_updated=%d, variable_log='%s' WHERE variable_name='%s' LIMIT 1", $value, $time, $log, $key);
      }else{
        $this->aVariable[$key] = array(
          'variable_value'    => $value,
          'variable_created'  => $time,
          'variable_updated'  => $time,
          'variable_log'      => $log
        );
        
        //CacheLib::set('pg_variable', $this->aVariable);
        
        return $database->db_query("INSERT INTO variables (variable_name, variable_value, variable_created, variable_updated, variable_log) VALUES ('%s', '%s', %d, %d, '%s')", $key, $value, $time, $time, $log);
      }
    }
    
    public function delete($key){
      if (isset($this->aVariable[$key])){
        return $database->db_query("DELETE FROM variables WHERE variable_name='%s' LIMIT 1)", $key);
      }
    }
}

?>